<?php 
	include ("gvar.php"); /*Load project global vars*/
	session_start(); /*Load current session vars*/ 
?>
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<link href="style.css" rel="stylesheet" type="text/css" />
<style>
.error {
	font-weight: bold;
	color: #C00;
}

</style>
</head>
<body>
	<div id="edit-box" class="login-box">
<?php

/*Don't allow anonymous; force only the logged users. Inversed interprets as... FALSE >> The user is logged || TRUE >> Not login*/
if(!HasLogged()) {
	print('<p class="error">403 -- You must be logged to upload this.</p></body></html>');
	exit;
}

/*Local debug controller; developement*/
/*error_reporting(E_ALL);
ini_set('display_errors', '1');*/
/* ---------------- */
/*Reconfig PHP exception case*/
ini_set('file_uploads', '1'); /*Allow file upload this time (exception)*/
ini_set('upload_tmp_dir', 'uploads_tmp'); /*TEMPORALY FILES; on fail case will result a trash. Is recommended to use different folder. (exception)*/
/*CONFIG BUG: Dosen't work forced, may be required edit manualy the config PHP*/
	/*ini_set('upload_max_filesize', '5242880');*/ /*In BYTES, the size max granted on upload file; if exceded, php deletes the file. -- DEFAULT IN SYSTEM PHP.INI: 2MB*/
	/*ini_set('post_max_size', '5242880');*/ /*In BYTES, declare the size allowed on send this POST, if exceeds will stop.*/
/*-----*/
/* ------------------------ */

if($_SERVER['REQUEST_METHOD'] == 'POST') { /*Sends data*/
	if (isset($_FILES['upload'])) { /*If any file has been sent...*/
		/*This "uploads/{$_FILES['uplo..." you can route another folder or what name to grant this. ie: "var/www/ftp/{$_FILES['upload']['name']}". Don't change ['upload'] for another, can break the system.*/
		if (move_uploaded_file($_FILES['upload']['tmp_name'], "uploads/{$_FILES['upload']['name']}")) { /*Upload success without error; MODIFY THIS ROUTE TO MOVE ANOTHER FOLDER.*/
			/*DBA -- SQL insert and values.*/
			//$usrname = $_SESSION["logID"]; /*Take the name user*/
			//$query = "INSERT INTO `File` (`UserName`) VALUES ('$usrname')"; /*SQL Insert (assumed MySQL ISO) with the Code as a integer autoincrement. Colum tested Code + UserName*/
			//$upinsert = mysql_query ($query, $dbserver) or die ("ERROR 500: Log file failed while add in the DB."); /*Log the file; on error: entry cannot be inserted in DB; this part requires to delete file but i din't know who.*/
			$fileName=$_FILES['upload']['name'];
			$actDate=$_POST['ActDate'];
			$dateExp=$_POST['DateExp'];
			$passwd=$_POST['Pass'];
			$Grade=$_POST['Grade'];
			$Subject=$_POST['Subject'];
			$user=$_SESSION['logID'];

			$gradeSelected ='SELECT * FROM Grade where Name= "'.$Grade.'"';  //Search what option is selected on the grade field
			if($r = mysql_query($gradeSelected,$dbc)) {
				while ($row = mysql_fetch_array($r, MYSQL_NUM)){
					$codeGrade=$row[0];
				}
			}
			$subjectSelected ='SELECT * FROM Subject WHERE Name="'.$Subject.'"';   //Search what option is selected on the subject field
			if($r = mysql_query($subjectSelected,$dbc)) {
				while ($row = mysql_fetch_array($r)){
					$codeSubject=$row[0];
				}
			}

			if(correctDate($actDate, $dateExp)){ //After do the insert, we want to control if dates entered are correct, in this case, we'll do the insert otherwise date error will be shown
				$insertQuery='INSERT INTO Files VALUES(0,"'.$fileName.'","'.$actDate.'","'.$dateExp.'","'.$passwd.'","'.$codeGrade.'","'.$codeSubject.'","'.$user.'");';
				$upinsert = mysql_query ($insertQuery, $dbc) or die ("ERROR 500: Log file failed while add in the DB."); /*Log the file; on error: entry cannot be inserted in DB; this part requires to delete file but i din't know who.**/

				echo '<p><em>El fitxer ha estat pujat correctament</em></p>'; print('<br/><p>Vol pujar qualque fitxer més?</p>');
			} else {
				echo '<p><em>Les dates introduïdes no pareixen ser correctes</em></p>';
			} 
		}
		else { echo '<p class="error">Ha ocorregut un error!<br/>'; } /*On error happens during upload in any case; warn simple error.*/
	}
	if($_FILES['upload']['error'] > 0) { /*On error ocurrs; tell what error during upload.*/
		switch ($_FILES['upload']['error']) { /*What case ocurred?*/
			case 1: /*Error caused by "upload_max_filesize"; loads more than configured*/
				print('El tamany del fitxer és superior al permés'); break;
			case 2: /*Error caused by in FORM the field named as "MAX_FILE_SIZE"; unknow case (no tested)*/
				print('The file size is long to upload'); break;
			case 3: /*Unknow much this, only says partially uploaded; unknow case (no tested)*/
				print('El procès de pujada ha estat aturat.'); break;
			case 4: /*No file given; submit but not declared the file to upload*/
				print('No s\'ha pujat cap fitxer'); break;
			/*case 5 not declared, unknow error case code 5*/
			case 6: /*Error caused by "upload_tmp_dir"; ocurrs if the route dosen't exist or haven't grant folder to write*/
				print('El directorio del servidor esta fora de servei'); break;
			case 7: /*Error caused by administrator; the folder's must have write permision to allow it. You have grant it?*/
				print('Error 500: Permís denegat de pujar i escriure al disc'); break;
			case 8: /*File upload aborted by client; unknow function (no tested)*/
				print('La pujada del fitxer s\'ha detengut per l\'usuari'); break;
			default: /*If the error is a rare unknow... ; unknow case (no tested)*/
				print('500: Internal server error, a unknow problem ocurrs in the system; call te administrator.'); break;
		}
		print('</p>'); /*html P class error closer*/
		echo '<input type="button" class="button" name="uploads" value="Torna enrera" onclick="location.href=\'upload.php\'"/>';
		exit; /*Stop the problem here.*/
	}
}

/*Form HTML (can upload another after finish); this input MAX_FILE_SIZE is needed, don't remove it*/
?>
<form enctype="multipart/form-data" action="upload.php" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="2097152" />
<fieldset><legend>Upload this file (max size: 2MB)</legend>
<p><b>File:</b> <input type="file" name="upload" /></p></fieldset>
<div>
	<?php
		$fileName=$_FILES['upload']['name'];
	?>
	<div>Data d'activació (AAAA-MM-DD): <input type="text" name="ActDate" size="40" maxsize="100" /></div>
	<div>Data d'expiració (AAAA-MM-DD): <input type="text" name="DateExp" size="40" maxsize="100" /></div>
	<div>Password: <input type="text" name="Pass" size="40" maxsize="100"/></div>
	<div>Curs: <select name="Grade" class="styled-select">
						<option value="">Seleccioni un curs</option>
						<?php 
							$grade = 'SELECT * FROM Grade';

							if($r = mysql_query($grade,$dbc)) {
								while ($row = mysql_fetch_array($r)){
									echo '<option value="'.$row['Name'].'">'.$row['Name'].'</option>';
								}
							}
					 	?>
				</select>
	</div>
	<div>Assignatura: <select name="Subject" class="styled-select">
						<option value="">Seleccioni una assignatura</option>
						<?php 
							$subject = 'SELECT * FROM Subject';

							if($r = mysql_query($subject,$dbc)) {
								while ($row = mysql_fetch_array($r)){
									echo '<option value="'.$row['Name'].'">'.$row['Name'].'</option>';
								}
							}
					 	?>
				</select>
	</div>
	<input type="hidden" name="id" value="' . $_GET['id'] . '" />
	<input type="submit" class="button" name="submit" value="Upload" />
	<input type="button" class="button" name="mainpage" value="Pàgina principal" onclick="location.href='index.php'"/>
</div>
</div>
</form>
</body>
</html>
